package models

import (
	"fmt"
	"github.com/astaxie/beego/orm"
	"strconv"
	"os/exec"
	"log"
	"io/ioutil"
)

type GateWay struct {
	Id               int64
	Gateway_name     string
	Gateway_group_id int64
	Max_concurrent   int
	Gateway_url      string
	Gateway_state    int
	Gateway_auth     string
	Call_gateway_id  int64
}

type CallGateWay struct {
	Id                         int64
	Gateway_name               string
	Gateway_url                string
	Call_prefix                string
	Max_call                   int
	Added_autodial             bool
	Effective_caller_id_number string
	Gateway_type               int
	Register_number            string
}

func (a *GateWay) TableName() string {
	return TableName("gateway")
}

func GateWayAdd(a *GateWay) (int64, error) {
	return orm.NewOrm().Insert(a)
}

func CallGateWayAdd(a CallGateWay) (int64,error) {
	splStr := "INSERT INTO call_gateway (gateway_name,gateway_url,call_prefix,max_call,effective_caller_id_number,gateway_type,register_number) VALUES ('" + a.Gateway_name +
		"','" + a.Gateway_url + "','" + a.Call_prefix + "'," + strconv.Itoa(a.Max_call) + "," +
		"'" + a.Effective_caller_id_number + "'," + strconv.Itoa(a.Gateway_type) + ",'" + a.Register_number + "')"+" RETURNING id"
	fmt.Println(splStr)
	var id int64
	err := orm.NewOrm().Raw(splStr).QueryRow(&id)
	updateCli()
	return id ,err
}

func CheckCallGateway(callGatewayId int64) (CallGateWay,error) {
	splStr := "select id,gateway_name,gateway_url,call_prefix,max_call,effective_caller_id_number,gateway_type,register_number FROM"+
	" call_gateway WHERE id="+strconv.FormatInt(callGatewayId,10)
	fmt.Println(splStr)
	var gateway CallGateWay
	err := orm.NewOrm().Raw(splStr).QueryRow(&gateway)
	if err != nil {
		return gateway,nil
	}
	return gateway ,err
}

func updateCli()  {
	// 执行系统命令
	// 第一个参数是命令名称
	// 后面参数可以有多个，命令参数
	cmd := exec.Command("fs_cli", "-x", "sofia profile external restart")
	// 获取输出对象，可以从该对象中读取输出结果
	stdout, err := cmd.StdoutPipe()
	if err != nil {
		log.Fatal(err)
	}
	// 保证关闭输出流
	defer stdout.Close()
	// 运行命令
	if err := cmd.Start(); err != nil {
		log.Fatal(err)
	}
	// 读取输出结果
	opBytes, err := ioutil.ReadAll(stdout)
	if err != nil {
		log.Fatal(err)
	}
	log.Println(string(opBytes))
}

func CallGateWayEdit(a CallGateWay) error {
	splStr := "UPDATE call_gateway SET  gateway_name='" + a.Gateway_name + "',gateway_url='" + a.Gateway_url + "'," +
		"call_prefix='" + a.Call_prefix + "',max_call=" + strconv.Itoa(a.Max_call) + "," +
		"effective_caller_id_number='" + a.Effective_caller_id_number + "'," +
		"gateway_type=" + strconv.Itoa(a.Gateway_type) + ",register_number='" + a.Register_number + "'" + " WHERE id=" + strconv.FormatInt(a.Id,10)
	fmt.Println(splStr)
	_, err := orm.NewOrm().Raw(splStr).Exec()
	updateCli()
	return err
}

func GateWayGetByName(gatewayName string) (*GateWay, error) {
	a := new(GateWay)
	err := orm.NewOrm().QueryTable(TableName("gateway")).Filter("gateway_name", gatewayName).One(a)
	if err != nil {
		return nil, err
	}
	return a, nil
}

func GateWayGetList(page, pageSize int, filters ...interface{}) ([]*GateWay, int64) {
	offset := (page - 1) * pageSize
	list := make([]*GateWay, 0)
	query := orm.NewOrm().QueryTable(TableName("gateway"))
	if len(filters) > 0 {
		l := len(filters)
		for k := 0; k < l; k += 2 {
			query = query.Filter(filters[k].(string), filters[k+1])
		}
	}
	total, _ := query.Count()
	query.OrderBy("-id").Limit(pageSize, offset).All(&list)

	return list, total
}

func GatewayIdName() ([]*GateWay, error) {
	list := make([]*GateWay, 0)
	query := orm.NewOrm().QueryTable(TableName("gateway"))
	_, err := query.OrderBy("-id").All(&list)

	if err != nil {
		return nil, err
	}
	return list, nil
}

func GateWayGetById(id int) (*GateWay, error) {
	r := new(GateWay)
	err := orm.NewOrm().QueryTable(TableName("gateway")).Filter("id", id).One(r)
	if err != nil {
		return nil, err
	}
	return r, nil
}

func (a *GateWay) Update(fields ...string) error {
	if _, err := orm.NewOrm().Update(a, fields...); err != nil {
		return err
	}
	return nil
}

func (a *GateWay) Delete() error {
	if _, err := orm.NewOrm().Delete(a); err != nil {
		return err
	}
	return nil
}
func CallDelete(id int64) error {
	splStr := "DELETE FROM call_gateway WHERE id ="+strconv.FormatInt(id,10)
	_,err := orm.NewOrm().Raw(splStr).Exec()
	if err != nil {
		return err
	}
	updateCli()
	return nil
}

func GetGateWayNameByUserId(userid int) ([]string, error) {
	authstr := " "
	if userid != 1 {
		authstr = "AND g.group_user_id=" + strconv.Itoa(userid)
	}
	strSql := "SELECT gw.gateway_name " +
		"FROM ai_gateway_group g,ai_gateway gw " +
		"WHERE g.id=gw.gateway_group_id " + authstr

	arr := make([]string, 0)
	_, err := orm.NewOrm().Raw(strSql).QueryRows(&arr)

	if err != nil {
		return arr, err
	}
	return arr, nil
}
